package br.edu.fasete.javaroad.plugin.gui.tablemodel;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.table.DefaultTableModel;

public class FileTableModel extends DefaultTableModel {
	private static String[] columns = {".", "Filename"};
	private Class[] classes = { Boolean.class, String.class};
	
	public FileTableModel() {
		super(columns, 0);
	}
	
	public String getColumnName(int arg0) {
		return columns[arg0];
	}

	public Class getColumnClass(int arg0) {
		return classes[arg0];
	}
	
	public void adicionarArquivo(String name, boolean selected) {
		Vector<Object> line = new Vector<Object>();
		File file = new File(name);
		line.add(new Boolean(selected));
		if(file.exists()) {
			line.add("<html><b><font color='#ff0000'>" + name + "</font></b></html>");	
		} else {
			line.add("<html><b><font color='#00ff00'>" + name + "</font></b></html>" );
		}
		super.addRow(line);
	}
	
	public void cleanTable() {
		while(this.getRowCount() > 0) {
			this.removeRow(0);
		}
	}
	
	public void selectAllFiles() {
		setAll(new Boolean(true), 0);
	}
	
	public void selectNoFile() {
		setAll(new Boolean(false), 0);
	}	
	
	public void selectInexistentFiles() {
		File file;
		int lineNumber = this.getRowCount();
		for(int i = 0; i < lineNumber; i++) {
			file = new File(removeHtml((String) getValueAt(i, 1)));
			if(file.exists()) {
				setValueAt(new Boolean(false), i, 0);
			}
			else {
				setValueAt(new Boolean(true), i, 0);
			}
		}	
	}
	
	
	private void setAll(Object value, int column) {
		int lineNumber = this.getRowCount();
		for(int i = 0; i < lineNumber; i++) {
			setValueAt(value, i, column);
		}			
		
	}
	
	public List<String> getFileList() {
		List<String> fileList = new ArrayList<String>();
		int lineNumber = this.getRowCount();
		for(int i = 0; i < lineNumber; i++) {
			Boolean sel = (Boolean) getValueAt(i, 0);
			if(sel.booleanValue()) {
				fileList.add(removeHtml((String)getValueAt(i, 1)));
			}
		}		
		return fileList;
	}
	
	
	
	public String removeHtml(String fileName) {
		return fileName.substring(31, fileName.length() - 18);
	}
	
}
